<?php
/**
 * Created by PhpStorm.
 * User: lichenchen
 * Date: 2018-8-5
 * Time: 10:16
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use think\facade\Env;

class Files extends AdminBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index($type=0, $page=1)
    {
        return $this->fetch('index');
    }

    public function up()
    {

        $config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,zip,mp4,flv'
        ];
        $file = $this->request->file('file');

        $upload_path = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads';
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);


        if ($info) {
            //写入文件到数据库
            $data = [
                'name' => $file->getInfo('name'),
                'size' => $file->getInfo('size'),
                'is_admin' => 1,
                'user_id' => session('admin_id'),
                'path' => str_replace('\\', '/', $save_path . $info->getSaveName()),
            ];
            //文件类型
            switch ($file->getInfo('type')){
                case 'image/jpg':
                    $data['type'] = 1;
                    break;
                case 'image/jpeg':
                    $data['type'] = 1;
                    break;

                case 'image/gif':
                    $data['type'] = 2;
                    break;
                case 'image/png':
                    $data['type'] = 3;

            }

            //写入数据库
            $files = \app\common\model\Files::create($data);


            $result = [
                'error' => 0,
                'file_id' => $files->id,
                'name' => $file->getInfo('name'),
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName()),
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);

    }

}